﻿using CommonBase;
using CommonClass;
using DAL;
using EnvCommonUtility;
using FileLib;
using Microsoft.Expression.Interactivity.Layout;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Win32;
using PersonnelLocationModule.Views;
using SurveillanceLib;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace PersonnelLocationModule.ViewModels
{
    /// <summary>
    /// 区域监控
    /// </summary>
    public class ViewModel_RegionSurveillance : WorkspaceViewModel
    {
        #region Const Fields

        private const string SITE_TOOLTIP = "『右键可查看详情』\n站点名称：{0}\n人员个数：{1} 个";
        private readonly string SAVEPATH_REGIONSURVEILLANCE;

        #endregion

        #region Private Fields

        private Canvas _canvasPanel;
        private TreeView _treeRegion; // 区域树
        private ITreeGroup _selectedTreeNode; // 所选结点
        private ISSDal _dataOperation = new ISSDal(); // 操作数据库
        private DelegateCommand _cmdSelectPicture, _cmdSave, _cmdCancel;

        private readonly IRegionManager _regionManager;

        #endregion

        #region Constructor

        public ViewModel_RegionSurveillance(Canvas canvasPanel,
            IRegionManager regionManager)
        {
            if (regionManager == null || canvasPanel == null)
                return;

            base.BaseRegionManager = regionManager;
            base.ViewName = SurveillancePro.Base.Common.ViewNames.PersonnelLocationModule_RegionSurveillance;
            base.HeaderTitle = "区域监控";
            base.HeaderImageSource = string.Format(ConstantString.IMAGE_URL, "Question");
            base.IsShowCloseButton = Visibility.Visible;

            this._regionManager = regionManager;
            this._canvasPanel = canvasPanel;

            SAVEPATH_REGIONSURVEILLANCE = SurveillanceUtilities.USERCONFIG_REGIONSURVEILLANCEPATH_DEFAULT;
            FileOperation.CreatDirectory(SAVEPATH_REGIONSURVEILLANCE); // 创建文件夹
            _loadRegionTreeData(); // 区域树加载
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Public Property

        /// <summary>
        /// 绑定树资源
        /// </summary>
        public ObservableCollection<ITreeGroup> TreeViewSource { get; set; }

        private bool _canControl;
        /// <summary>
        /// 按钮组可以使用与否
        /// </summary>
        public bool CanControl
        {
            get { return _canControl; }
            set
            {
                if (_canControl == value) return;
                _canControl = value;
                base.OnPropertyChanged("CanControl");
            }
        }

        private string _pictureURL;
        /// <summary>
        /// 图片路径
        /// </summary>
        public string PictureURL
        {
            get { return _pictureURL; }
            set
            {
                if (_pictureURL == value) return;
                _pictureURL = value;
                base.OnPropertyChanged("PictureURL");


                try
                {
                    if (string.IsNullOrWhiteSpace(value))
                        _pictureSource = null;
                    else
                        _pictureSource = new BitmapImage(new Uri(
                            value, UriKind.RelativeOrAbsolute));
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                    _pictureSource = null;
                }
                finally
                {
                    base.OnPropertyChanged("PictureSource");
                }
            }
        }

        private BitmapImage _pictureSource;
        /// <summary>
        /// 图片资源
        /// </summary>
        public BitmapImage PictureSource
        {
            get
            {
                return _pictureSource;
            }
        }

        /// <summary>
        /// 图片选择
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_SelectPicture
        {
            get
            {
                if (_cmdSelectPicture == null)
                {
                    _cmdSelectPicture = new DelegateCommand(_selectPicture, _canSelectPicture);
                }
                return _cmdSelectPicture;
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Save
        {
            get
            {
                if (_cmdSave == null)
                {
                    _cmdSave = new DelegateCommand(_save, _canSave);
                }
                return _cmdSave;
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Cancel
        {
            get
            {
                if (_cmdCancel == null)
                {
                    _cmdCancel = new DelegateCommand(_cancel, _canCancel);
                }
                return _cmdCancel;
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// 双击叶子结点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (!(sender is TreeView) || (sender as TreeView).SelectedItem == null ||
                    !((sender as TreeView).SelectedItem is ITreeGroup) ||
                    !(((sender as TreeView).SelectedItem as ITreeGroup).Arg is ArgModel) ||
                    ((sender as TreeView).SelectedItem as ITreeGroup).Level == 0) // 只有叶子结点有效
                    return;

                this._canvasPanel.Children.Clear(); // 清空容器中的区域站点点位
                CanControl = true; // 按钮组可用
                _treeRegion = sender as TreeView; // 记录区域树
                _selectedTreeNode = _treeRegion.SelectedItem as ITreeGroup; // 记录所选结点，注：TreeView 没有 SelectedItem 公开属性，只有 get 访问器！
                ArgModel regionArg = _selectedTreeNode.Arg as ArgModel;

                DataTable sites = Utilities.GetDataTable(
                    string.Format(ISSDal.QUERY_GET_ALLSITEDATA_BYREGIONID, regionArg.sKey), null); // 获得区域站点信息
                if (string.IsNullOrWhiteSpace(regionArg.sValue)) // 无图片时
                    PictureURL = string.Empty;
                else
                    PictureURL = Path.Combine(SAVEPATH_REGIONSURVEILLANCE, regionArg.sValue); // 获得图片路径

                if (sites != null)
                {
                    DataTable employees; // 区域站点人员列表
                    Dictionary<string, string> employeeIDs; // 区域站点人员列表 ID，进入区域站点时间
                    double x = 0.0, y = 0.0; // 记录坐标

                    for (int i = 0; i < sites.Rows.Count; i++)
                    {
                        if (sites.Rows[i]["SiteID"] == null)
                            continue;

                        #region 解析并记录原始坐标
                        if (sites.Rows[i]["X"] == null ||
                            string.IsNullOrWhiteSpace(sites.Rows[i]["X"].ToString()) ||
                            !double.TryParse(sites.Rows[i]["X"].ToString(), out x))
                            x = 30.0 * i; // 防止站台重合
                        if (sites.Rows[i]["Y"] == null ||
                            string.IsNullOrWhiteSpace(sites.Rows[i]["Y"].ToString()) ||
                            !double.TryParse(sites.Rows[i]["Y"].ToString(), out y))
                            y = 0.0;
                        #endregion

                        employees = Utilities.GetDataTable(
                            string.Format(ISSDal.QUERY_GET_ALLEMPLOYEESTATEDATA_BYSITEID, sites.Rows[i]["SiteID"]), 
                            null); // 获得区域站点人员个数

                        employeeIDs = new Dictionary<string, string>();
                        foreach (DataRow employee in employees.Rows)
                        {
                            if (employee["EmpID"] != null)
                                employeeIDs.Add(employee["EmpID"].ToString(), employee["EnterTime"].ToString()); // 添加区域站点人员 ID，进入区域站点时间
                        }

                        // 动态创建站点
                        RegionSiteView sitePoint = new RegionSiteView();
                        ViewModel_RegionSite vmRegionSite = new ViewModels.ViewModel_RegionSite(
                            this._regionManager, employeeIDs);
                        sitePoint.DataContext = vmRegionSite;

                        if (vmRegionSite != null)
                        {
                            vmRegionSite.SiteID = sites.Rows[i]["SiteID"].ToString();
                            vmRegionSite.RegionID = sites.Rows[i]["RegionID"].ToString();
                            vmRegionSite.SiteName = (sites.Rows[i]["SiteName"] != null && !string.IsNullOrWhiteSpace(sites.Rows[i]["SiteName"].ToString())) ?
                                sites.Rows[i]["SiteName"].ToString() : "无名称"; // 站点名称
                            vmRegionSite.RegionName = _selectedTreeNode.Name; // 区域名称
                        }

                        sitePoint.ToolTip = string.Format(SITE_TOOLTIP,
                            vmRegionSite.SiteName, employees.Rows.Count); // Tooltip：站点名称；站点人员个数

                        Canvas.SetLeft(sitePoint, x); // 设置左边界
                        Canvas.SetTop(sitePoint, y); // 设置上边界
                        _attachMouseDragElementBehavior(sitePoint); // 可拖动元素
                    }
                }
                else
                {
                    MessageBox.Show("没有对应的站点信息！", ConstantString.MSG_COMPANY);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canSelectPicture()
        {
            return true;
        }

        private bool _canSave()
        {
            return true;
        }

        private bool _canCancel()
        {
            return true;
        }


        /// <summary>
        /// 图片选择
        /// </summary>
        private void _selectPicture()
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Filter = "Jpeg Files (*.jpg)|*.jpg|Png Files (*.png)|*.png|Bmp Files (*.bmp)|*.bmp|Icon Files (*.ico)|*.ico",
                Multiselect = false,
                Title = "选择图片",
            };

            if (dialog.ShowDialog() != true)
                return;
            PictureURL = dialog.FileName;
        }

        /// <summary>
        /// 保存
        /// </summary>
        private void _save()
        {
            try
            {
                Point regionSitePoint; // 站点相对位置
                Dictionary<string, Point> sitesDic = new Dictionary<string, Point>(); // 站点 ID，站点坐标

                foreach (FrameworkElement regionSite in this._canvasPanel.Children)
                {
                    // 获取区域站点的相对位置
                    regionSitePoint = regionSite.TranslatePoint(new Point(0, 0), this._canvasPanel); // 或：regionSitePoint = regionSite.TransformToAncestor(this._canvasPanel).Transform(new Point(0, 0));
                    ViewModel_RegionSite vmRegionSite = regionSite.DataContext as ViewModel_RegionSite;
                    if (vmRegionSite != null)
                    {
                        sitesDic.Add(vmRegionSite.SiteID, regionSitePoint); // 添加站点点位信息
                    }
                }

                // 复制文件到项目文件夹中便于项目可移植
                if (FileOperation.IsExistFile(PictureURL) &&
                    !string.IsNullOrWhiteSpace(FileOperation.GetFileName(PictureURL)) && 
                    !string.IsNullOrWhiteSpace(SAVEPATH_REGIONSURVEILLANCE))
                {
                    try
                    {
                        string destFileName = Path.Combine(SAVEPATH_REGIONSURVEILLANCE,
                            FileOperation.GetFileName(PictureURL)); // 生成目标文件路径
                        FileOperation.CopyFile(PictureURL, destFileName); // 拷贝文件到指定目录
                        PictureURL = destFileName; // 重新定义新的图片路径
                    }
                    catch (System.Exception ex)
                    {
#if DEBUG
                        Debug.WriteLine(ex.Message);
#endif
                    }
                }

                // 更新数据库操作
                if (_selectedTreeNode != null &&
                    _selectedTreeNode.Arg != null &&
                    _selectedTreeNode.Arg is ArgModel &&
                    !string.IsNullOrWhiteSpace((_selectedTreeNode.Arg as ArgModel).sKey))
                {
                    ArgModel regionArg = _selectedTreeNode.Arg as ArgModel;
                    int regionResult = _dataOperation.EditRegionItem(regionArg.sKey, 
                        FileOperation.GetFileName(PictureURL)); // 更新 Region 表图片相对路径

                    if (regionResult > 0)
                    {
                        regionArg.sValue = FileOperation.GetFileName(PictureURL); // 修改保存的图片路径

                        if (sitesDic != null &&
                            sitesDic.Count <= 0) // 没有区域站点的情况
                        {
                            MessageBox.Show("操作成功！", ConstantString.MSG_COMPANY);
                            return;
                        }

                        int siteResult = _dataOperation.EditSiteItem(sitesDic); // 更新 Site 表坐标

                        if (siteResult > 0)
                            MessageBox.Show("操作成功！", ConstantString.MSG_COMPANY);
                        else
                            MessageBox.Show("操作失败！", ConstantString.MSG_COMPANY);
                    }
                    else
                        MessageBox.Show("操作失败！", ConstantString.MSG_COMPANY);
                }
                else
                    MessageBox.Show("操作失败！", ConstantString.MSG_COMPANY);
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void _cancel()
        {
            TreeView_MouseDoubleClick(this._treeRegion, null); // 类似重新双击结点
        }

        #endregion

        #region 添加行为

        /// <summary>
        /// 添加鼠标拖动行为
        /// </summary>
        /// <param name="element">被拖动元素</param>
        private void _attachMouseDragElementBehavior(UIElement element)
        {
            if (this._canvasPanel == null)
            {
#if DEBUG
                Debug.WriteLine("区域容器为空！");
#endif
                return;
            }

            this._canvasPanel.Children.Add(element); // 将元素添加到区域容器中
            MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
            dragBehavior.Attach(element);
            dragBehavior.ConstrainToParentBounds = true; // 不允许拖出父元素容器
        }

        #endregion

        /// <summary>
        /// 加载区域树
        /// </summary>
        private void _loadRegionTreeData()
        {
            try
            {
                if (TreeViewSource != null)
                    TreeViewSource.Clear();

                EnvTreeViewOperation _treeOpertion = new EnvTreeViewOperation();
                TreeGroupModel node = new TreeGroupModel(string.Empty, new ObservableCollection<ITreeGroup>());
                _treeOpertion.AddRegionTreeView(0, node, (TreeGroupModel)null,
                    "db_VWMSConnectionString", string.Format("{0}.exe", System.Windows.Forms.Application.ProductName)); // 获取树节点，构建区域树

                TreeViewSource = node.Leaves; // 绑定到树资源
                base.OnPropertyChanged("TreeViewSource");
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            if (TreeViewSource != null)
                TreeViewSource.Clear();
        }

        #endregion
    }
}
